package cn.edu.uestc.cwdsj.utils;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Date;

public class GsonUtil {
    private GsonUtil() {
    }

    /**
     * 一个静态gson的工厂方法
     * 提供将java.util.Date转化成毫秒时间戳的gson
     * 和 毫秒时间戳转化为Date
     *
     * @return 将java.util.Date转化成毫秒时间戳的gson
     */
    public static Gson getTsGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Date.class, new EDate2MilliTsTypeAdapter());
        gsonBuilder.registerTypeAdapter(Date.class, new EMilliTs2DateTypeAdapter());
        return gsonBuilder.create();
    }

    private static class EDate2MilliTsTypeAdapter implements JsonSerializer<Date> {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            if (src != null) {
                return new JsonPrimitive(src.getTime());
            }
            return null;
        }
    }

    private static class EMilliTs2DateTypeAdapter implements JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            if (json != null) {
                return new Date(json.getAsJsonPrimitive().getAsLong());
            }
            return null;
        }
    }
}
